<template>
	<view class="tn-safe-area-inset-bottom">
		<!-- 顶部自定义导航 -->
		<tn-nav-bar fixed alpha customBack>
			<view slot="back" class='tn-custom-nav-bar__back'>
				<text class='icon tn-icon-left' @click="goBack"></text>
				<text class='icon tn-icon-home-capsule-fill' @click="goHome"></text>
			</view>
		</tn-nav-bar>

		<view class="tn-margin-top" :style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<!-- 这个是图鸟UI响应用户需求，推出的一个uni_modules组件，插件市场点击右上角，导入即可 https://ext.dcloud.net.cn/plugin?id=10172 -->
			<wx-user-info-modal v-model="showAuthorizationModal" @updated="updatedUserInfoEvent"></wx-user-info-modal>

			<view class="tn-flex tn-flex-row-between tn-strip-bottom tn-padding" @tap.stop="openAuthorizationModal">
				<view class="justify-content-item">
					<view class="tn-text-bold tn-text-lg ">
						{{vuex_user.username}}
					</view>
					<view v-if="vuex_user.userId" class="tn-color-gray tn-padding-top-xs">
						ID：{{vuex_user.userId}}
					</view>
				</view>
				<view class="justify-content-item tn-text-lg tn-color-grey">
					<view class="logo-pic tn-shadow">
						<view class="logo-image">
							<view class="tn-shadow-blur"
								:style="'background-image:url('+vuex_user.headImg+');width: 80rpx;height: 80rpx;background-size: cover;'">
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- <view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding" @click="showModal1">
				<view class="justify-content-item">
					<view class="tn-text-bold tn-text-lg">
						昵称
					</view>
					<view class="tn-color-gray tn-padding-top-xs">
						{{userInfo.username}}
					</view>
				</view>
				<view class="justify-content-item tn-text-lg tn-color-grey">
					<view class="tn-icon-right tn-padding-top"></view>
				</view>
			</view> -->

			<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding" @click="showModalBindEmail">
				<view class="justify-content-item">
					<view class="tn-text-bold tn-text-lg">
						绑定邮箱
					</view>
					<view class="tn-color-gray tn-padding-top-xs">
						{{vuex_user.email?vuex_user.email:'未绑定'}}
					</view>
				</view>
				<view class="justify-content-item tn-text-lg tn-color-grey">
					<view class="tn-icon-right tn-padding-top"></view>
				</view>
			</view>


			<picker @change="bindPickerChangeSex" range-key="text" :value="sexIndex" :range="sexList">
				<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
					<view class="justify-content-item">
						<view class="tn-text-bold tn-text-lg">
							性别
						</view>
						<view class="tn-color-gray tn-padding-top-xs">

							<view class="tn-color-gray">{{sexList[sexIndex]?sexList[sexIndex].text:''}}</view>
						</view>
					</view>
					<view class="justify-content-item tn-text-lg tn-color-grey">
						<view class="tn-icon-right tn-padding-top"></view>
					</view>
				</view>
			</picker>
			<picker @change="bindDateChange" mode="date" :value="vuex_user.birthday" :start="startDate" :end="endDate">
				<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
					<view class="justify-content-item">
						<view class="tn-text-bold tn-text-lg">
							生日
						</view>
						<view v-if="vuex_user.birthday" class="tn-color-gray tn-padding-top-xs">
							{{vuex_user.birthday}}
						</view>
					</view>
					<view class="justify-content-item tn-text-lg tn-color-grey">
						<view class="tn-icon-right tn-padding-top"></view>
					</view>
				</view>
			</picker>
			<picker @change="bindPickerChangeCons" range-key="text" :value="consIndex" :range="constellationList">
				<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
					<view class="justify-content-item">
						<view class="tn-text-bold tn-text-lg">
							星座
						</view>
						<view v-if="vuex_user.constellation && constellationList[consIndex]" class="tn-color-gray tn-padding-top-xs">
							{{constellationList[consIndex].text}}
						</view>
					</view>
					<view class="justify-content-item tn-text-lg tn-color-grey">
						<view class="tn-icon-right tn-padding-top"></view>
					</view>
				</view>
			</picker>

			<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding" @click="showIntroModal">
				<view class="justify-content-item">
					<view class="tn-text-bold tn-text-lg">
						个性签名
					</view>
					<view v-if="vuex_user.introduce" class="tn-color-gray tn-padding-top-xs">
						{{vuex_user.introduce}}
					</view>
				</view>
				<view class="justify-content-item tn-text-lg tn-color-grey">
					<view class="tn-icon-right tn-padding-top"></view>
				</view>
			</view>



			<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding" @click="showModalPassword">
				<view class="justify-content-item">
					<view class="tn-text-bold tn-text-lg">
						修改密码
					</view>
				</view>
				<view class="justify-content-item tn-text-lg tn-color-grey">
					<view class="tn-icon-right tn-padding-top"></view>
				</view>
			</view>
			
			<!-- <tn-list-cell :hover="true" :unlined="true" :radius="true" :fontSize="32" @click="showModalPassword">
				<view class="tn-flex tn-flex-col-center tn-text-bold tn-margin-top-sm">
					<view class=" tn-flex-1 tn-text-center">修改密码</view>
				</view>
			</tn-list-cell> -->
			

			<tn-modal v-model="showPassword" :custom="true" :showCloseBtn="true">
				<view class="custom-modal-content">
					<view class="">
						<view class="tn-text-lg tn-text-bold tn-color-purplered tn-text-center tn-padding">修改密码</view>
						<view class="tn-bg-gray--light"
							style="border-radius: 10rpx;padding: 20rpx 30rpx;margin: 50rpx 0 60rpx 0;">
							<tn-input clearable v-model="updatePasswordParam.oldPassword" placeholder="旧密码, 未设置可不填"
								name="input" type="password" placeholder-style="color:#AAAAAA"
								:maxLength="20"></tn-input>

						</view>
						<view class="tn-bg-gray--light"
							style="border-radius: 10rpx;padding: 20rpx 30rpx;margin: 50rpx 0 60rpx 0;">
							<tn-input clearable v-model="updatePasswordParam.newPassword" placeholder="输入新密码"
								name="input" type="password" placeholder-style=" color:#AAAAAA"
								:maxLength="20"></tn-input>

						</view>
					</view>
					<view class="tn-flex-1 justify-content-item tn-margin-sm tn-text-center">
						<tn-button @click="savePassword" backgroundColor="#3668FC" padding="40rpx 0" width="60%"
							fontBold>
							<text class="tn-color-white">保 存</text>
						</tn-button>
					</view>
				</view>
			</tn-modal>

			<tn-modal v-model="showBindEmail" :custom="true" :showCloseBtn="true">
				<view class="custom-modal-content">
					<view class="">
						<view class="tn-text-lg tn-text-bold tn-color-purplered tn-text-center tn-padding">绑定邮箱</view>

						<view class="tn-bg-gray--light"
							style="border-radius: 10rpx;padding: 20rpx 30rpx;margin: 50rpx 0 60rpx 0;">
							<tn-input clearable v-model="bindEmailParam.email" placeholder="输入邮箱" name="input"
								placeholder-style="color:#AAAAAA" :maxLength="64"></tn-input>
						</view>


						<view class="tn-bg-gray--light"
							style="border-radius: 10rpx;padding: 20rpx 30rpx;margin: 50rpx 0 60rpx 0;">
							<view class="tn-flex tn-flex-direction-column tn-flex-direction-row">
								<tn-input v-model="bindEmailParam.captcha" placeholder="输入验证码" name="input"
									placeholder-style="color:#AAAAAA" :maxLength="64"></tn-input>
								<tn-button @click="getEmailCode" class="tn-flex-center" backgroundColor="#01BEFF"
									fontColor="#FFFFFF" size="sm" padding="5rpx 10rpx" type='number'
									shape="round">{{tips}}</tn-button>
							</view>
						</view>
					</view>

					<view class="tn-flex-1 justify-content-item tn-margin-sm tn-text-center">
						<tn-button @click="saveBindEmail" backgroundColor="#3668FC" padding="40rpx 0" width="60%"
							fontBold>
							<text class="tn-color-white">确认绑定</text>
						</tn-button>
					</view>

				</view>
			</tn-modal>

			<tn-modal v-model="showUnbindEmail" :custom="true" :showCloseBtn="true">
				<view class="custom-modal-content">
					<view class="">
						<view class="tn-text-lg tn-text-bold tn-color-purplered tn-text-center tn-padding">解绑邮箱</view>

						<view class="tn-bg-gray--light"
							style="border-radius: 10rpx;padding: 20rpx 30rpx;margin: 50rpx 0 60rpx 0;">
							<view class="tn-flex tn-flex-direction-column tn-flex-direction-row">
								<tn-input v-model="unbindEmailParam.captcha" placeholder="输入验证码" name="input"
									placeholder-style="color:#AAAAAA" type='number' :maxLength="6"></tn-input>
								<tn-button @click="getEmailCode" class="tn-flex-center" backgroundColor="#01BEFF"
									fontColor="#FFFFFF" size="sm" padding="5rpx 10rpx"
									shape="round">{{tips}}</tn-button>
							</view>
						</view>
					</view>

					<view class="tn-flex-1 justify-content-item tn-margin-sm tn-text-center">
						<tn-button @click="saveUnbindEmail" backgroundColor="#3668FC" padding="40rpx 0" width="60%"
							fontBold>
							<text class="tn-color-white">确认解绑</text>
						</tn-button>
					</view>

				</view>
			</tn-modal>


			<!-- <tn-modal v-model="show2" :custom="true" :showCloseBtn="true">
				<view class="custom-modal-content">
					<view class="">
						<view class="tn-text-lg tn-text-bold tn-color-purplered tn-text-center tn-padding">变更手机号码</view>
						<view class="tn-bg-gray--light tn-color-gray"
							style="border-radius: 10rpx;padding: 20rpx 30rpx;margin: 50rpx 0 60rpx 0;">
							13911111193
						</view>
					</view>
					<view class="tn-flex-1 justify-content-item tn-margin-sm tn-text-center">
						<tn-button backgroundColor="#3668FC" padding="40rpx 0" width="60%" fontBold
							open-type="getPhoneNumber">
							<text class="tn-color-white">获取手机号</text>
						</tn-button>
					</view>
				</view>
			</tn-modal> -->

			<tn-modal v-model="showIntroModel" :custom="true" :showCloseBtn="true">
				<view class="custom-modal-content">
					<view class="">
						<view class="tn-text-lg tn-text-bold tn-color-purplered tn-text-center tn-padding">
							请输入个性签名
						</view>
						<view class="tn-bg-gray--light"
							style="border-radius: 10rpx;padding: 20rpx 30rpx;margin: 50rpx 0 60rpx 0;">
							<tn-input clearable v-model="introduce" placeholder="请输入个性签名,100字以内" name="input"
								placeholder-style="color:#AAAAAA" :maxLength="100"></tn-input>
						</view>
					</view>
					<view class="tn-flex-1 justify-content-item tn-margin-sm tn-text-center">
						<tn-button @click="saveIntroDuce" backgroundColor="#3668FC" padding="40rpx 0" width="60%"
							fontBold>
							<text class="tn-color-white">保 存</text>
						</tn-button>
					</view>
				</view>
			</tn-modal>

		</view>
		<!-- 验证码倒计时 -->
		<tn-verification-code ref="code" uniqueKey="bind-email" :seconds="60" @change="codeChange" />

	</view>
</template>

<script>
	import validator from "@/utils/validateUtil.js"
	import {
		resetPasswordByUser,
		sendBindEmailCaptcha,
		sendUnbindEmailCaptcha,
		bindEmail,
		unbindEmail
	} from "@/api/auth.js"
	import {
		getMyInfo,
		updateUserInfo
	} from "@/api/user.js"
	import {
		getDictDataList
	} from '@/utils/dictUtil.js';

	import template_page_mixin from '@/libs/mixin/template_page_mixin.js'

	import {
		uploadAvatar
	} from '@/utils/uploadUtil.js'
	import WxUserInfoModal from '@/uni_modules/tuniaoui-wx-user-info/components/tuniaoui-wx-user-info/tuniaoui-wx-user-info.vue'
	export default {
		components: {
			WxUserInfoModal
		},
		name: 'TemplateSet',
		mixins: [template_page_mixin],
		data() {
			return {
				tips: '获取验证码',
				showBindEmail: false,
				showUnbindEmail: false,
				// 修改密码 请求参数
				updatePasswordParam: {
					oldPassword: null,
					newPassword: null
				},
				userInfo: {},
				showAuthorizationModal: false,
				showPassword: false,
				// 昵称
				username: '',
				show2: false,
				// 介绍
				introduce: '',
				showIntroModel: false,
				// 性别
				sexIndex: 0,
				sexList: [],
				// 星座
				consIndex: 0,
				constellationList: [],
				// 绑定邮箱 请求参数
				bindEmailParam: {
					emial: '',
					captcha: '',
					code: ''
				},
				unbindEmailParam: {
					captcha: '',
					code: ''
				}
			}
		},
		created() {
			if (!this.vuex_user) {
				return
			}
			this.getMyInfoData()
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		methods: {
			// 绑定邮箱
			saveBindEmail() {
				if (!validator.email(this.bindEmailParam.email)) {
					return
				}
				if (!validator.captcha(this.bindEmailParam.captcha)) {
					return
				}
				bindEmail(this.bindEmailParam).then(res => {
					this.$t.message.toast('绑定成功')
					this.showBindEmail = false
					this.userInfo.email = this.bindEmailParam.email
					this.syncLocalUserInfo()
					this.bindEmailParam = {}
				})
			},
			// 解绑邮箱
			saveUnbindEmail() {
				if (!validator.captcha(this.unbindEmailParam.captcha)) {
					return
				}
				unbindEmail(this.unbindEmailParam).then(res => {
					this.$t.message.toast('解绑成功')
					this.showUnbindEmail = false
					this.userInfo.email = null
					this.syncLocalUserInfo()
					this.unbindEmailParam = {}
				})
			},
			// 修改密码
			savePassword() {
				if (!validator.password(this.updatePasswordParam.newPassword)) {
					return
				}
				resetPasswordByUser(this.updatePasswordParam).then(res => {
					this.$t.message.toast('密码更改成功')
					this.showPassword = false
					this.updatePasswordParam = {}
				})
			},
			getMyInfoData() {
				getMyInfo().then(res => {
					this.userInfo = res.data
					this.introduce = this.userInfo.introduce

					this.sexList = getDictDataList("gender")
					this.constellationList = getDictDataList("constellation")

					this.sexIndex = this.getArrIndexById(this.userInfo.sex, this.sexList)
					this.consIndex = this.getArrIndexById(this.userInfo.constellation, this.constellationList)
					this.syncLocalUserInfo()
				})
			},
			// 保存签名
			saveIntroDuce() {
				this.userInfo.introduce = this.introduce
				this.showIntroModel = false
				this.updateUserInfoData()
			},
			// 更新信息
			updateUserInfoData() {
				updateUserInfo(this.userInfo).then(() => {
					this.syncLocalUserInfo()
				})
			},
			syncLocalUserInfo() {
				// 更新vuex
				this.$t.vuex('vuex_user', {
					...this.vuex_user,
					...this.userInfo
				})
			},
			getArrIndexById(id, arr) {
				if (!id) {
					return 0;
				}
				for (let index in arr) {
					if (arr[index].dictValue === id + '') {
						return index;
					}
				}
				return 0;
			},
			// 跳转
			tn(e) {
				uni.navigateTo({
					url: e,
				});
			},

			// 弹出模态框
			showModalPassword(event) {
				this.openModal1()
			},
			// 打开模态框
			openModal1() {
				this.showPassword = true
			},

			// 弹出邮箱绑定
			showModalBindEmail(event) {
				if (this.vuex_user.email) {
					this.showUnbindEmail = true
				} else {
					this.showBindEmail = true
				}
			},


			// 弹出模态框
			showIntroModal(event) {
				this.showIntroModel = true
				this.introduce = this.userInfo.introduce ? this.userInfo.introduce : ''
			},

			bindPickerChangeSex: function(e) {
				this.sexIndex = e.detail.value
				this.userInfo.sex = this.sexList[this.sexIndex].dictValue
				this.updateUserInfoData()
			},

			bindPickerChangeCons: function(e) {
				this.consIndex = e.detail.value
				this.userInfo.constellation = this.constellationList[this.consIndex].dictValue
				this.updateUserInfoData()
			},

			bindDateChange: function(e) {
				this.userInfo.birthday = e.detail.value
				this.updateUserInfoData()
			},

			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
					month = month > 9 ? month : '0' + month;
					day = day > 9 ? day : '0' + day;
				} else if (type === 'end') {
					// 最晚当天
				}

				return `${year}-${month}-${day}`;
			},

			// 打开获取用户信息弹框
			openAuthorizationModal() {
				this.showAuthorizationModal = true
			},

			// 获取到的用户信息
			async updatedUserInfoEvent(info) {
				// 没修改，不更新
				if (this.userInfo.username === info.nickname && this.userInfo.headImg === info.avatar) {
					this.showAuthorizationModal = false
					return
				}

				// 关系昵称
				if (this.userInfo.username !== info.nickname) {
					this.userInfo.username = info.nickname
				}

				// 更新头像
				if (this.userInfo.headImg !== info.avatar) {
					await uploadAvatar(info.avatar).then(fileUrl => {
						if (fileUrl) {
							this.userInfo.headImg = fileUrl
						}
					})
				}
				// 发起更新请求，并关闭弹窗
				await this.updateUserInfoData()
				this.showAuthorizationModal = false
			},
			// 获取验证码倒计时被修改
			codeChange(event) {
				this.tips = event
			},
			// 获取验证码
			getEmailCode() {
				if (this.$refs.code.canGetCode) {
					if (this.vuex_user.email) {
						// 有邮箱，获取解绑验证码
						this.getEmailCodeByUnbindEmail()
					} else {
						// 没邮箱，获取绑定验证码
						this.getEmailCodeByBindEmail()
					}
				} else {
					this.$t.message.toast(this.$refs.code.secNum + '秒后再重试')
				}
			},
			// 获取绑定验证码
			getEmailCodeByBindEmail() {
				if (!validator.email(this.bindEmailParam.email)) {
					return
				}
				this.$t.message.loading('正在获取验证码')
				this.bindEmailParam.code = Date.now().toString()
				sendBindEmailCaptcha({
					email: this.bindEmailParam.email,
					code: this.bindEmailParam.code
				}).then(res => {
					this.$t.message.closeLoading()
					this.$t.message.toast('验证码已经发送')
					this.$refs.code.start()
				})
			},
			// 获取解绑验证码
			getEmailCodeByUnbindEmail() {
				this.$t.message.loading('正在获取验证码')
				this.unbindEmailParam.code = Date.now().toString()
				sendUnbindEmailCaptcha({
					code: this.unbindEmailParam.code
				}).then(res => {
					this.$t.message.closeLoading()
					this.$t.message.toast('验证码已经发送')
					this.$refs.code.start()
				})
			}

		},
	}
</script>

<style lang="scss" scoped>
	/* 胶囊*/
	.tn-custom-nav-bar__back {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		box-sizing: border-box;
		background-color: rgba(0, 0, 0, 0.15);
		border-radius: 1000rpx;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		color: #FFFFFF;
		font-size: 18px;

		.icon {
			display: block;
			flex: 1;
			margin: auto;
			text-align: center;
		}

		&:before {
			content: " ";
			width: 1rpx;
			height: 110%;
			position: absolute;
			top: 22.5%;
			left: 0;
			right: 0;
			margin: auto;
			transform: scale(0.5);
			transform-origin: 0 0;
			pointer-events: none;
			box-sizing: border-box;
			opacity: 0.7;
			background-color: #FFFFFF;
		}
	}

	/* 授权 */
	.login-page {
		width: 100vw;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 授权按钮 */
	.submit-btn {
		width: 100%;
		background-color: #05C160;
		color: #FFFFFF;
		margin-top: 60rpx;
		border-radius: 10rpx;
		padding: 25rpx;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 30rpx;
	}

	/* 间隔线 start*/
	.tn-strip-bottom-min {
		width: 100%;
		border-bottom: 1rpx solid #F8F9FB;
	}

	.tn-strip-bottom {
		width: 100%;
		border-bottom: 20rpx solid rgba(241, 241, 241, 0.8);
	}

	/* 间隔线 end*/


	/* 用户头像 start */
	.logo-image {
		width: 80rpx;
		height: 80rpx;
		position: relative;
	}

	.logo-pic {
		background-size: cover;
		background-repeat: no-repeat;
		// background-attachment:fixed;
		background-position: top;
		border: 2rpx solid rgba(255, 255, 255, 0.05);
		box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.15);
		border-radius: 50%;
		overflow: hidden;
		// background-color: #FFFFFF;
	}


	/* 底部悬浮按钮 start*/
	.tn-tabbar-height {
		min-height: 100rpx;
		height: calc(120rpx + env(safe-area-inset-bottom) / 2);
	}

	.tn-footerfixed {
		position: fixed;
		width: 100%;
		bottom: calc(30rpx + env(safe-area-inset-bottom));
		z-index: 1024;
		box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0);

	}

	/* 底部悬浮按钮 end*/
</style>